package emulator.hardware.io.peripherals;

import java.util.Observable;

import emulator.hardware.bits.SharedBit;
import emulator.hardware.io.Via6522;

public class Joystick extends Observable
{
	SharedBit[] button_state = new SharedBit[5];
	JoystickButton[] button = new JoystickButton[5];
	
	public final static int BUTTON_FIRE = 1;
	public final static int BUTTON_LEFT = 2; 
	public final static int BUTTON_RIGHT = 4; 
	public final static int BUTTON_UP = 8; 
	public final static int BUTTON_DOWN = 16;
	
	public JoystickButton getButton(int index)
	{
		return button[index];
	}
	
	public void attachToVia(Via6522 via_keyboard, Via6522 via_joystick)
	{
		button_state[0] = via_joystick.getPortA().getInPortBit(5);
		button_state[1] = via_joystick.getPortA().getInPortBit(4);
		button_state[2] = via_keyboard.getPortB().getInPortBit(7);
		button_state[3] = via_joystick.getPortA().getInPortBit(2);
		button_state[4] = via_joystick.getPortA().getInPortBit(3);
		for (int i = 0; i < button.length; i++)
		{
			button_state[i].setValue(true);
			button[i] = new JoystickButton(i, this);
		}
	}
	
	public void updatePosition(int direction)
	{
		for (int i = 0; i < button_state.length; i++)
			button_state[i].setValue((direction & (1 << i)) != 0);
		setChanged();
		notifyObservers();
	}
	
	public void updateButton(int index, boolean value)
	{
		button_state[index].setValue(value);
		setChanged();
		notifyObservers();
	}

	public boolean getState(int index) {
		return button_state[index].getValue();
	}
}
